<template>
  <div class="pay">
    <!-- 地址相关 -->
    <div class="address">
      <div class="left-icon">
        <van-icon name="logistics" />
      </div>

      <div class="info" v-show=" Object.keys(defaultAddress).length !== 0">
        <el-select v-model="defaultAddress" style="width: 240px" v-show="isselected" @change="isselected=false">
          <el-option v-for="item in address" :key="item" :label="formatAddressLabel(item)" :value="item">
          </el-option>
        </el-select>
        <div class="selected-info" v-show="!isselected" @click="isselected = true">
          <div class="info-content">
            <span class="name">{{user.username}}</span>&nbsp;&nbsp;&nbsp;
            <span class="mobile">{{defaultAddress.phone}}</span>
          </div>
          <div class="info-address">
            {{defaultAddress.city+defaultAddress.province+defaultAddress.detail}}
          </div>
        </div>
      </div>

      <div class="info" v-show=" Object.keys(defaultAddress).length === 0">
        <el-button plain @click="dialogFormVisible = true">
          请添加配送地址
        </el-button>
      </div>

      <div class="right-icon">
        <van-icon name="plus" @click="dialogFormVisible = true" />
      </div>
    </div>

    <!-- 订单明细 -->
    <div class="pay-list">
      <div class="list">
        <div class="goods-item" v-for="(item, index) in cart" :key="index" v-show="item.checked">
          <div class="left">
            <img :src="item.picture" alt="" />
          </div>
          <div class="right">
            <p class="tit text-ellipsis-2">
              {{  item.goods_name  }}
            </p>
            <p class="info">
              <span class="count">x{{ item.num }}</span>
              <span class="price">¥{{ (item.goods_price*item.num).toFixed(1) }}</span>
            </p>
          </div>
        </div>
      </div>

      <div class="flow-num-box">
        <span>共 {{ cartCheckedCount()||0 }} 件商品，合计：</span>
        <span class="money">￥{{ total.toFixed(1) }}</span>
      </div>

      <div class="pay-detail">
        <div class="pay-cell">
          <span>订单总金额：</span>
          <span class="red">￥{{ total.toFixed(1)}}</span>
        </div>

        <div class="pay-cell">
          <span>优惠券：</span>
          <span>无优惠券可用</span>
        </div>

        <div class="pay-cell">
          <span>配送费用：</span>
          <span v-if="defaultAddress.length === 0">请先选择配送地址</span>
          <span v-else class="red">+￥0.00</span>
        </div>
      </div>

      <!-- 支付方式 -->
      <div class="pay-way">
        <span class="tit">支付方式</span>
        <div class="pay-cell">
          <span><van-icon name="balance-o" />微信支付</span>
          <span class="red"><van-icon name="passed" /></span>
        </div>
      </div>

      <!-- 买家留言 -->
      <div class="buytips">
        <textarea placeholder="选填：买家留言（50字内）" v-model="remark" cols="30" rows="10"></textarea>
      </div>
    </div>

    <!-- 底部提交 -->
    <div class="footer-fixed">
      <div class="left">实付款：<span>￥{{total.toFixed(1)}}</span></div>
      <div class="tipsbtn" @click="submitOrder" v-show="defaultAddress.length !== 0">提交订单</div>
    </div>
  </div>
  //添加地址
  <el-dialog v-model="dialogFormVisible" title="添加收货地址" width="300">
  <el-form :model="form">
    <!-- 省 -->
    <el-form-item label="省" :label-width="formLabelWidth">
      <el-input v-model="form.province" placeholder="广东省" autocomplete="off" />
    </el-form-item>

    <!-- 市 -->
    <el-form-item label="市" :label-width="formLabelWidth">
      <el-input v-model="form.city" placeholder="广州市" autocomplete="off" />
    </el-form-item>

    <!-- 区 -->
    <el-form-item label="区" :label-width="formLabelWidth">
      <el-input v-model="form.detail" placeholder="广东技术师范大学" autocomplete="off" />
    </el-form-item>

    <!-- 电话 -->
    <el-form-item label="电话" :label-width="formLabelWidth">
      <el-input v-model="form.telephone" placeholder="110" autocomplete="off" />
    </el-form-item>
  </el-form>
  <template #footer>
    <div class="dialog-footer">
      <el-button @click="dialogFormVisible = false">取消</el-button>
      <el-button type="primary" @click="addAddress()">
        确定
      </el-button>
    </div>
  </template>
</el-dialog>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import useCart from '@/stores/cart';
import useAddress from '@/stores/address'
import useUser from '@/stores/user';
const { cart, cartCount, cartCheckedCount } = useCart()
const { address, loadAddress, addressValue } = useAddress()
const { user } =useUser()
const defaultAddress = ref({})
//生命周期钩子
onMounted(async()=>{
  await loadPageInfo()
})

//加载页面内容
const loadPageInfo = async() =>{
  loadAddress()
  // console.log(address);
  defaultAddress.value = addressValue().length > 0 ? address[0] : {};
  // console.log(addressValue().value);
  
  // console.log(defaultAddress.value);
}

//计算总商品数
const total = computed(() => {
    let sum = 0
    cart.forEach(item => {
        if (item.checked) {
            sum += item.goods_price * item.num
        }
    })
    return sum
})


const dialogFormVisible = ref(false)
const formLabelWidth = '50px'

const form = ref({
  province : '',
  city: '',
  detail: '',
  telephone: ''
})
import { addAddressInfo } from '@/api';
import { showToast } from 'vant';

//添加收货地址
const addAddress = async() =>{
  console.log(form.value);
  const data = await addAddressInfo({ province: form.value.province, city: form.value.city, detail: form.value.detail, phone: form.value.telephone })
  window.location.reload()
}

const isselected = ref(false)
// 格式化地址标签
const formatAddressLabel = (item) => {
  // 格式化 username 显示第一个字和两个星号
  const formattedUsername = user.username.charAt(0) + '**'
  
  // 格式化 phone 显示前三个数字和后四个，中间部分用两个星号代替
  const formattedPhone = item.phone.slice(0, 3) + '****' + item.phone.slice(-4)

  // 返回格式化后的显示内容
  return `${formattedUsername} ${formattedPhone} ${item.province} ${item.city} ${item.detail}`
}

import router from "@/router"
import { buyCart, addOrder, updateOrderInfo } from '@/api';

const remark= ref('')

const submitOrder = async() =>{
  if(cartCheckedCount()!==0){
    const data = await addOrder({ total_amount: total.value.toFixed(1), remarks: remark.value})
    cart.forEach(async item=>{
      if(item.checked){
        const goods_id=item.goods_id
        const num = item.num
        const order_id=data.data
        console.log(order_id);
        await updateOrderInfo({ goods_id, num, order_id  })
        await buyCart({ goods_id })
    }
    setTimeout(() => {
      router.push('/cart')
    }, 3000);
  })
}
}
</script>

<style lang="less" scoped>
/* 原样保持样式不变 */
.pay {
  padding-top: 10px;
  padding-bottom: 46px;
  ::v-deep {
    .van-nav-bar__arrow {
      color: #333;
    }
  }
}
.address {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 20px;
  font-size: 14px;
  color: #666;
  position: relative;
  background: url(@/assets/border-line.png) bottom repeat-x;
  background-size: 60px auto;
  .left-icon {
    margin-right: 20px;
  }
  .right-icon {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-7px);
  }
}
.goods-item {
  height: 100px;
  margin-bottom: 6px;
  padding: 10px;
  background-color: #fff;
  display: flex;
  .left {
    width: 100px;
    img {
      display: block;
      width: 80px;
      margin: 10px auto;
    }
  }
  .right {
    flex: 1;
    font-size: 14px;
    line-height: 1.3;
    padding: 10px;
    padding-right: 0px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    color: #333;
    .info {
      margin-top: 5px;
      display: flex;
      justify-content: space-between;
      .price {
        color: #fa2209;
      }
    }
  }
}

.flow-num-box {
  display: flex;
  justify-content: flex-end;
  padding: 10px 10px;
  font-size: 14px;
  border-bottom: 1px solid #efefef;
  .money {
    color: #fa2209;
  }
}

.pay-cell {
  font-size: 14px;
  padding: 10px 12px;
  color: #333;
  display: flex;
  justify-content: space-between;
  .red {
    color: #fa2209;
  }
}
.pay-detail {
  border-bottom: 1px solid #efefef;
}

.pay-way {
  font-size: 14px;
  padding: 10px 12px;
  border-bottom: 1px solid #efefef;
  color: #333;
  .tit {
    line-height: 30px;
  }
  .pay-cell {
    padding: 10px 0;
  }
  .van-icon {
    font-size: 20px;
    margin-right: 5px;
  }
}

.buytips {
  display: block;
  textarea {
    display: block;
    width: 100%;
    border: none;
    font-size: 14px;
    padding: 12px;
    height: 100px;
  }
}

.footer-fixed {
  position: fixed;
  background-color: #fff;
  left: 0;
  bottom: 0;
  width: 100%;
  height: 46px;
  line-height: 46px;
  border-top: 1px solid #efefef;
  font-size: 14px;
  display: flex;
  .left {
    flex: 1;
    padding-left: 12px;
    color: #666;
    span {
      color:#fa2209;
    }
  }
  .tipsbtn {
    width: 121px;
    background: linear-gradient(90deg,#f9211c,#ff6335);
    color: #fff;
    text-align: center;
    line-height: 46px;
    display: block;
    font-size: 14px;
  }
}
</style>